/*
 * @Description: 一网通办项目封装统一请求接口
 * @Author: smileswlin
 * @LastEditor: smileswlin
 * @Date: 2020-06-17 20:57:12
 * @LastEditTime: 2020-06-26 21:03:44
 */
import config from '@govcloud/gsd-web-core-config'
// import { getAccessToken } from '..'
import { logout } from '../business/logout'
import { request, requestFd, requestAccessLayer } from './request'

/**
 * @description: 拦截器失败回调，接口未登录则跳转登录页，否则都reject
 * @return:
 * @param error
 */
function reject(error) {
  if (
    error[config.apiReturnDefine.errcode] === 400000401 &&
    window.location.pathname !== '/orgDev/rz/index.html'
  ) {
    // 接口返回未登录编码并且不在登录页时，则跳转登录页
    logout()
  }
  return Promise.reject(error)
}

/**
 * 统一封装处理两种请求
 * @param req
 * @param option
 * @param custom
 * @returns {*}
 */
function processApi(req, option = {}, custom) {
  // 方便后续统一处理入口
  // 废弃，后端改为httponly的cookies了
  // if (getAccessToken()) {
  //   // 回塞accessToken到头部
  //   option.headers = Object.assign(option.headers || {}, {
  //     Authorization: getAccessToken() || ''
  //   })
  // }

  /**
   * 自定义拦截器处理逻辑
   */
  /**
   * 处理request拦截器
   */
  req.interceptors.request.use(reqConfig => {
    if (
      custom &&
      custom.request &&
      custom.request.resolve &&
      typeof custom.request.resolve === 'function'
    ) {
      return custom.request.resolve(reqConfig)
    }
    return reqConfig
  }, custom && custom.request && custom.request.reject)

  /**
   * 处理response拦截器
   */
  req.interceptors.response.use(res => {
    if (
      custom &&
      custom.response &&
      custom.response.resolve &&
      typeof custom.response.resolve === 'function'
    ) {
      return custom.response.resolve(res)
    }
    return res
  }, (custom && custom.response && custom.response.reject) || reject)

  console.log('====> request', option)
  return req(option)
}

/**
 * @description: application/json接口请求
 * @return:
 * @param option  {Object}
 * @param custom  {Object}
 */
function fetchApi(option = {}, custom) {
  // 方便后续统一处理入口
  // debugger
  return processApi(request, option, custom)
}

function fetchAccessApi(option = {}, custom) {
  return processApi(requestAccessLayer, option, custom)
}

/**
 * @description: form-data接口请求
 * @return:
 * @param option  {Object}
 * @param custom  {Object}
 */
function fetchApiFd(option = {}, custom) {
  return processApi(requestFd, option, custom)
}

export { fetchApi, fetchApiFd, fetchAccessApi }
